package com.br.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.br.dao.SalasDao;
import com.br.model.Jogador;
import com.br.model.Sala;
import com.br.util.StopUtils;

@WebServlet(value = "/ListarSalas")
public class ListarSalas extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static Logger logger = LogManager.getLogger(ListarSalas.class.getName());

	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		Jogador eu = (Jogador) req.getSession(true).getAttribute("jogador");
		if(eu == null){
			logger.debug("Sessao nao iniciada!");
			return;
		}
		
		logger.debug("INIT "+StopUtils.logAllParameters(req));

		SalasDao dao = new SalasDao();
		// busca as salas criadas
		List<Sala> salas = dao.list();

		JSONObject response = new JSONObject();

		try {
			if (salas.size() == 0) {

				response.put("error", true);
				response.put("errorMsg", "Não existem salas criadas.");

			} else {
				// Month a response
				JSONArray jsonSalas = new JSONArray();
				for (int i = 0; i < salas.size(); i++) {
					Sala sala = salas.get(i);
					JSONObject jsonSala = new JSONObject();
					jsonSala.put("uid", sala.getUid());
					jsonSala.put("nome", sala.getNome());
					jsonSala.put("vagas", sala.getQntVagas());
					jsonSala.put("jogadores", sala.getJogadores().size());
					jsonSalas.put(jsonSala);
				}

				response.put("error", false);
				response.put("salas", jsonSalas);
			}
		} catch (JSONException e) {
			logger.error("Erro JSON", e);
		}

		// retorna o json
		res.setContentType("application/json");
		res.setCharacterEncoding("UTF-8");
		res.getOutputStream().write(response.toString().getBytes());
		res.getOutputStream().flush();
		
		logger.debug("END "+response.toString());
	}

}
